package com.sx.pipeline.ui.needs.construction.add

import android.Manifest
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.DialogPasswordInput
import com.sx.pipeline.databinding.ActConstructionNeedsAddBinding
import com.sx.pipeline.ui.needs.construction.ConstructionNeedsVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 施工单位 发布需求
 */
@Route(path = RoutePath.Mine.CONSTRUCTION_NEEDS_ADD)
class ConstrucationNeedsAddActivity :
    CYDataBindingBaseActivity<ActConstructionNeedsAddBinding, ConstructionNeedsVM>(R.layout.act_construction_needs_add),
    View.OnClickListener {
    @JvmField
    @Autowired(name = IntentKey.ID)
    var needsId: Int? = 0

    private var longitude: String = "" //经度
    private var latitude: String = "" //纬度
    private var addressDetail: String = "" //详细地址
    private var startTime: String = "" //开始时间
    private var endTime: String = "" //结束时间

    private var price: String = "" //管币价格

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //如果isEdit=true 为重新提交  请求接口
        if (needsId != 0) {
            mBinding.titleBar.setTitle("编辑需求")
            needsId?.let { mViewModel.getNeedOrderDetail(it) }
        }


        //联系人默认是本人
        mBinding.etPrincipal.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)
        //请求需求类型数据
        mViewModel.getNeed()
        //请求联系人列表
        mViewModel.getContacts()
        //请求单位信息
        mViewModel.getUserUnit()
        //获取发布供应价格
        mViewModel.getNeedPrice()
        initUploadAttach()

    }

    override fun initViewObservable() {
        super.initViewObservable()
        //单位信息数据
        observe(mViewModel.userUnitEvent) {
            mBinding.sbUnitName.rightText = it?.name
        }

        observe(mViewModel.locationEvent) {
            longitude = it?.latLonPoint?.longitude.toString()
            latitude = it?.latLonPoint?.latitude.toString()
            addressDetail = it?.snippet.toString()
            mBinding.sbArea.rightText = "${it?.title.toString()} ${it?.snippet.toString()}"
        }

        //图片上传结果
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageUploadAttachment.addImage(it)
        }

        //编辑数据
        observe(mViewModel.needOrderDetailEvent) {
            mBinding.sbTitle.rightText = it?.title
            mBinding.etDesc.setText(it?.description)
            mBinding.etProjectName.setText(it?.name)
            mBinding.sbRequirementType.rightText = it?.needType
            mBinding.etNeedNum.setText(it?.omsNeedServe?.quantity)
            mBinding.sbMeasurementUnit.rightText = it?.omsNeedServe?.unit
            mBinding.sbArea.rightText = it?.addressDetail
            mBinding.sbNatureTask.rightText = it?.omsNeedServe?.nature
            mBinding.sbStartTime.rightText = it?.omsNeedServe?.startDate
            mBinding.sbEndTime.rightText = it?.omsNeedServe?.endDate
            mBinding.sbSettlementMethod.rightText = it?.omsNeedServe?.paymentMethod
            mBinding.etPrincipal.setText(it?.contact)
            mBinding.etContactPhone.setText(it?.contactPhone)
            longitude = it?.longitude.toString()
            latitude = it?.latitude.toString()
            startTime = it?.omsNeedServe?.startDate.toString()
            endTime = it?.omsNeedServe?.endDate.toString()

            if (!TextUtils.isEmpty(it?.omsNeedServe?.appendixUrl)) {
                val imageList = it?.omsNeedServe?.appendixUrl?.split(",")
                if (imageList != null) {
                    for (i in imageList) {
                        mBinding.imageUploadAttachment.addImage(i)
                    }
                }
            }

        }

        //获取发布需求管币价格
        observe(mViewModel.needPriceEvent) {
            if (it?.toInt() != 0) {
                price = it.toString()
                mBinding.tvMoney.text = it.toString() + "管币"
                mBinding.tabPrice.visibility = View.VISIBLE
            }

        }
    }

    fun initUploadAttach() {
        // 上传图片
        mBinding!!.imageUploadAttachment.initAdapter(3, 3)
        mBinding!!.imageUploadAttachment.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@ConstrucationNeedsAddActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageUploadAttachment.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap =
                                        BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@ConstrucationNeedsAddActivity,
                                        inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageUploadAttachment.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap =
//                                            BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@ConstrucationNeedsAddActivity,
//                                            inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //选择标题
            R.id.sb_title -> {
                if (mViewModel.needTitleData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_select_request_title))
                popup.setPickerData(mViewModel.needTitleData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbTitle.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择计量单位
            R.id.sb_measurement_unit -> {
                if (mViewModel.needUnitData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup =
                    CustomCommonPicket(this, getString(R.string.txt_choose_measurement_unit))
                popup.setPickerData(mViewModel.needUnitData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbMeasurementUnit.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择任务性质
            R.id.sb_nature_task -> {
                if (mViewModel.needNatureData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_nature_task))
                popup.setPickerData(mViewModel.needNatureData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbNatureTask.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择需求类型
            R.id.sb_requirement_type -> {
                if (mViewModel.needTypeData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_need_type))
                popup.setPickerData(mViewModel.needTypeData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbRequirementType.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_principal))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etPrincipal.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择结算方式
            R.id.sb_settlement_method -> {
                if (mViewModel.settleMethodData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup =
                    CustomCommonPicket(this, getString(R.string.txt_select_settlement_method))
                popup.setPickerData(mViewModel.settleMethodData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.sbSettlementMethod.rightText = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            R.id.sb_start_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择开始时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        startTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbStartTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.sb_end_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择结束时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        endTime = AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                        mBinding.sbEndTime.rightText =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.sb_area -> {
                // 选择施工地点
                PermissionHelper.requestTip(this,"选择施工地点需要授权定位权限",object :PermissionUtils.SimpleCallback{
                    override fun onGranted() {
                        RouteManager.Main.intentToSearchLocation()

                    }

                    override fun onDenied() {
                        ToastUtils.showShort("请授权后再继续操作")
                    }
                },Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)
//                PermissionX.init(this)
//                    .permissions(
//                        Manifest.permission.ACCESS_FINE_LOCATION,
//                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//                    )
//                    .onExplainRequestReason { scope, deniedList ->
//                        scope.showRequestReasonDialog(
//                            deniedList,
//                            "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                            "确认",
//                            "取消"
//                        )
//                    }
//                    .onForwardToSettings { scope, deniedList ->
//                        scope.showForwardToSettingsDialog(
//                            deniedList,
//                            "您需要手动在“设置”中允许必要的权限",
//                            "确定",
//                            "取消"
//                        )
//                    }
//                    .request { allGranted, grantedList, deniedList ->
//                        if (allGranted) {
//                            RouteManager.Main.intentToSearchLocation()
//                        } else {
//                            Toast.makeText(
//                                this,
//                                "这些权限被拒绝,可能影响管建宝正常使用"+": $deniedList",
//                                Toast.LENGTH_LONG
//                            ).show()
//                        }
//                    }
            }
            R.id.tv_commit -> {
                if (TextUtils.isEmpty(mBinding.sbTitle.rightText.toString())) {
                    ToastUtils.showShort("请选择标题")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etProjectName.text.toString())) {
                    ToastUtils.showShort("请输入项目名称")
                    return
                }
                if (TextUtils.isEmpty(mBinding.sbRequirementType.rightText.toString())) {
                    ToastUtils.showShort("请选择需求类型")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etNeedNum.text.toString())) {
                    ToastUtils.showShort("请填写需求量")
                    return
                }
                if (TextUtils.isEmpty(mBinding.sbMeasurementUnit.rightText.toString())) {
                    ToastUtils.showShort("请选择计量单位")
                    return
                }
                if (TextUtils.isEmpty(addressDetail) && TextUtils.isEmpty(longitude) && TextUtils.isEmpty(
                        latitude
                    )
                ) {
                    ToastUtils.showShort("请选择需求服务地点")
                    return
                }
                if (TextUtils.isEmpty(mBinding.sbNatureTask.rightText.toString())) {
                    ToastUtils.showShort("请选择任务性质")
                    return
                }
                if (TextUtils.isEmpty(startTime)) {
                    ToastUtils.showShort("请选择开始时间")
                    return
                }
                if (TextUtils.isEmpty(endTime)) {
                    ToastUtils.showShort("请选择结束时间")
                    return
                }
                if (TextUtils.isEmpty(mBinding.sbSettlementMethod.rightText.toString())) {
                    ToastUtils.showShort("请选择结算方式")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etPrincipal.text.toString())) {
                    ToastUtils.showShort("请选择联系人")
                    return
                }
                if (TextUtils.isEmpty(mBinding.etContactPhone.text.toString())) {
                    ToastUtils.showShort("请填写联系电话")
                    return
                }



                if (needsId == 0) {
                    //无密码
                    if (TextUtils.isEmpty(price)) {
                        //提交 添加需求
                        mViewModel.addConstructionNeedOrder(
                            mBinding.sbTitle.rightText.toString(),
                            mBinding.etDesc.text.toString(),
                            mBinding.etProjectName.text.toString(),
                            mBinding.sbRequirementType.rightText.toString(),
                            mBinding.etNeedNum.text.toString(),
                            mBinding.sbMeasurementUnit.rightText.toString(),
                            longitude,
                            latitude,
                            mBinding.sbArea.rightText.toString(),
                            mBinding.sbNatureTask.rightText.toString(),
                            startTime,
                            endTime,
                            mBinding.sbSettlementMethod.rightText.toString(),
                            mBinding.etPrincipal.text.toString(),
                            mBinding.etContactPhone.text.toString(),
                            AndroidUtil.listToString(mBinding.imageUploadAttachment.imagePath)
                                .toString(),
                            ""
                        )
                    } else {
                        val popup =
                            DialogPasswordInput(
                                this,
                                price.toString()
                            ).setPassInputListener { pass ->
                                //提交 添加需求
                                mViewModel.addConstructionNeedOrder(
                                    mBinding.sbTitle.rightText.toString(),
                                    mBinding.etDesc.text.toString(),
                                    mBinding.etProjectName.text.toString(),
                                    mBinding.sbRequirementType.rightText.toString(),
                                    mBinding.etNeedNum.text.toString(),
                                    mBinding.sbMeasurementUnit.rightText.toString(),
                                    longitude,
                                    latitude,
                                    mBinding.sbArea.rightText.toString(),
                                    mBinding.sbNatureTask.rightText.toString(),
                                    startTime,
                                    endTime,
                                    mBinding.sbSettlementMethod.rightText.toString(),
                                    mBinding.etPrincipal.text.toString(),
                                    mBinding.etContactPhone.text.toString(),
                                    AndroidUtil.listToString(mBinding.imageUploadAttachment.imagePath)
                                        .toString(),
                                    pass
                                )
                            }
                        XPopup.Builder(this)
                            .borderRadius(42f)
                            .isDarkTheme(false)
                            .asCustom(popup)
                            .show()
                    }


                } else {
                    //提交 编辑需求
                    needsId?.let {
                        mViewModel.editConstructionNeedOrder(
                            it,
                            mViewModel.needOrderDetailEvent.value?.omsNeedServe!!.id,
                            mBinding.sbTitle.rightText.toString(),
                            mBinding.etDesc.text.toString(),
                            mBinding.etProjectName.text.toString(),
                            mBinding.sbRequirementType.rightText.toString(),
                            mBinding.etNeedNum.text.toString(),
                            mBinding.sbMeasurementUnit.rightText.toString(),
                            longitude,
                            latitude,
                            mBinding.sbArea.rightText.toString(),
                            mBinding.sbNatureTask.rightText.toString(),
                            startTime,
                            endTime,
                            mBinding.sbSettlementMethod.rightText.toString(),
                            mBinding.etPrincipal.text.toString(),
                            mBinding.etContactPhone.text.toString(),
                            AndroidUtil.listToString(mBinding.imageUploadAttachment.imagePath)
                                .toString()
                        )
                    }
                }

            }
        }
    }

}